// PreferencesPlugin.kt
package com.sanji.capture_audio.plugin

import android.app.Activity
import android.net.Uri
import com.sanji.capture_audio.utils.Preferences
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler

/**
 * PreferencesPlugin 是一个 Flutter 插件，用于管理应用的偏好设置。
 * 它实现了 FlutterPlugin 和 ActivityAware 接口，以便在 Flutter 和原生 Android 之间进行通信。
 */
class PreferencesPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    // 用于与 Flutter 通信的 MethodChannel
    private var channel: MethodChannel? = null
    
    // 当前的 Activity 实例
    private var activity: Activity? = null
    
    // 偏好设置管理器实例
    private var preferences: Preferences? = null

    companion object {
        // 插件的通道名称
        const val PLUGIN_CHANNEL = "preferences"
    }

    /**
     * 当插件附加到 Flutter 引擎时调用
     * @param flutterPluginBinding Flutter 插件绑定对象
     */
    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(
            flutterPluginBinding.binaryMessenger,
            PLUGIN_CHANNEL
        )
        channel?.setMethodCallHandler(this)
    }

    /**
     * 处理来自 Flutter 的方法调用
     * @param call 方法调用对象
     * @param result 方法调用结果回调
     */
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (activity == null) {
            result.error("NO_ACTIVITY", "Activity is not available", null)
            return
        }

        if (preferences == null) {
            preferences = Preferences(activity!!)
        }
        
        when (call.method) {
            "setEnabled" -> {
                // 设置启用状态
                val enabled = call.arguments as? Boolean ?: false
                preferences?.isEnabled = enabled
                result.success(null)
            }
            "getEnabled" -> {
                // 获取启用状态
                result.success(preferences?.isEnabled)
            }
            "getOpeningStatement" -> {
                // 获取开场白（opening statement）的 URI
                val uri = preferences?.openingStatement?.toString()
                result.success(uri)
            }
            "setRecordingEnabled" -> {
                // 设置录音是否启用
                val enabled = call.arguments as? Boolean ?: false
                preferences?.isRecordingEnabled = enabled
                result.success(null)
            }
            "getRecordingEnabled" -> {
                // 获取录音是否启用
                result.success(preferences?.isRecordingEnabled)
            }
            "getRecordingOutputFile" -> {
                // 获取录音输出文件的 URI
                val uri = preferences?.recordingOutputFile?.toString()
                result.success(uri)
            }
            else -> result.notImplemented()
        }
    }

    /**
     * 当插件从 Flutter 引擎分离时调用
     * @param binding Flutter 插件绑定对象
     */
    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel?.setMethodCallHandler(null)
        channel = null
    }

    /**
     * 当插件附加到 Activity 时调用
     * @param binding Activity 插件绑定对象
     */
    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
        preferences = Preferences(activity!!)
    }

    /**
     * 当插件从 Activity 分离时调用
     */
    override fun onDetachedFromActivity() {
        activity = null
        preferences = null
    }

    /**
     * 当 Activity 因配置更改重新附加时调用
     * @param binding Activity 插件绑定对象
     */
    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    /**
     * 当 Activity 因配置更改分离时调用
     */
    override fun onDetachedFromActivityForConfigChanges() {
        onDetachedFromActivity()
    }
}